package org.jeecg.modules.file;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.jeecg.common.api.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/oss/file")
public class DeleteFile {

    private static Logger logger = LoggerFactory.getLogger(DeleteFile.class);

    @DeleteMapping("/del")
    public Result deleteFile(@RequestParam String url) {
        // 创建OSSClient实例（OSS客户端实例）
        OSS ossClient = new OSSClientBuilder().build(OssConfig.ENDPOINT,
                OssConfig.KEY_ID, OssConfig.KEY_SECRET);

        //文件名（服务器上的文件路径）
        String host = "https://" + OssConfig.BUCKET_NAME + "." + OssConfig.ENDPOINT + "/";
        String objectName = url.substring(host.length());

        // 判断是否删除成功
        boolean deleteFileSucceed = false;

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(OssConfig.BUCKET_NAME, objectName);

            deleteFileSucceed = true;
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message:" + oe.getErrorMessage());
            logger.info("Error Code:" + oe.getErrorCode());
            logger.info("Request ID:" + oe.getRequestId());
            logger.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        if (deleteFileSucceed) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }
}
